﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using Complaint.Models.Dtos.Validators;

namespace Complaint.Models.Dtos
{
    public class AgreedToTncValidationAttribute : ValidationAttribute 
    { 
        public override bool IsValid(object value) 
        { 
            return (bool)value; 
        } 
    }

    public partial class Complaint : IEntity
    {
        [AgreedToTncValidation(ErrorMessage = "Please agree to our terms and conditions")]
        public bool AgreedToTnc { get; set; }

        public Complaint()
        {
            DateLodged = DateTime.Now;
        }

        #region Implementation of IEntity

        public bool IsValid
        {
            get { return (GetRuleViolations().Count() == 0); }
        }

        public IEnumerable<RuleViolation> GetRuleViolations()
        {
            if (String.IsNullOrEmpty(Title))
                yield return new RuleViolation("Title is required", "Title");

            if (String.IsNullOrEmpty(Body))
            {
                yield return new RuleViolation("Complaint is required", "Body");
            }

            if (!String.IsNullOrEmpty(Body))
                if (Body.Length > 8000)
                    yield return new RuleViolation("Max body length is 8000 characters", "Body");

            if (Organisation == null)
            {
                yield return new RuleViolation("Please select an organisation first");
            }

            if (!AgreedToTnc)
                yield return new RuleViolation("Please agree to our terms and conditions", "AgreedToTnc");
        }

        #endregion

        /// <summary>
        /// Returns a boolean value indicating whether a complaint is settled.
        /// </summary>
        /// <returns>True or false</returns>
        public bool IsSettled
        {
            get
            {
                return Settlement.Count > 0;
            }
        }

        /// <summary>
        /// Returns a boolean value indicating if a complaint is lodged by a given user. It depends on a pre loaded User property, 
        /// otherwise NullReferenceException would be thrown.
        /// </summary>
        /// <param name="userName">The userName of a user</param>
        /// <returns>True of false</returns>
        /// <remarks>Dependent on pre loaded User property.</remarks>
        /// <exception cref="NullReferenceException">NullReferenceException</exception>
        public bool IsLodgedBy(string userName)
        {
            return User.Email.Equals(userName, StringComparison.InvariantCultureIgnoreCase);
        }
    }
}
